package com.yantong.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.yantong.constant.OrderStatus;
import com.yantong.constant.ProductType;
import com.yantong.controller.BaseController;
import com.yantong.mapper.OrderProductMapper;
import com.yantong.pojo.*;
import com.yantong.pojo.vo.CartDelallVo;
import com.yantong.pojo.vo.SalesStockVo;
import com.yantong.result.ResultVo;
import com.yantong.service.*;
import com.yantong.utils.ValidateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: juzi
 * @date: 2021/10/25
 * @time: 16:12
 */
@ApiIgnore
@Controller
@RequestMapping("/wxapi/product")
public class ApiProductController extends BaseController {


    @Autowired
    ProductCentreService productCentreService;
    @Autowired
    MemberService memberService;
    @Autowired
    OrderService orderService;
    @Autowired
    MarketingSeckillService marketingSeckillService;
    @Autowired
    MarketingGroupService marketingGroupService;
    @Autowired
    ProductCommentService productCommentService;
    @Autowired
    OrderProductMapper orderProductMapper;
    @Autowired
    CentreService centreService;


    /**
     * 添加商品评论
     *
     * @param comment
     * @return
     */
    @RequestMapping("/comment/add")
    @ResponseBody
    public ResultVo addComment(ProductComment comment) {
        ResultVo resultVo = new ResultVo();
        //用户信息
        Member member = memberService.getByKey(comment.getMid());
        if (member == null) {
            return ResultVo.error("添加评价失败！");
        }
        comment.setHeadimgurl(member.getAvatar());
        comment.setNickname(member.getNickname());
        comment.setOpenid(member.getOpenid());
        comment.setMid(member.getId());

        if (null != comment.getImageList() && comment.getImageList().size() > 0) {
            //评论图片处理
            String imgs = "";
            for (String img : comment.getImageList()) {
                imgs += img + ",";
            }
            imgs = imgs.substring(0, imgs.length() - 1);
            comment.setImages(imgs);
        }
        //订单信息
        Order order = orderService.getByKey(comment.getOrderid().longValue());
        if (order == null) {
            return ResultVo.error("查询订单信息失败，请重试！");
        } else if (order.getOrderType() == ProductType.Spellgroup.getType()) {
            //拼团商品
        }
        List<OrderProduct> ops = orderService.getOrderProductListByOrdId(order.getId());
        Long centreId = order.getCentreId();
        if(comment.getType() == 0){
            if (!order.getStatus().equals(OrderStatus.delivery_success.getCode()) &&
                    !order.getStatus().equals(OrderStatus.work_access.getCode())) {
                return ResultVo.error("订单未完成，提交评价失败！");
            }
            if (null != ops && ops.size() > 0) {
                for (OrderProduct orderProduct : ops) {
                    //商品信息
                    ProductCentre detail = productCentreService.getProductDetail(orderProduct.getProductId());
                    if (detail == null) {
                        continue;
                    }
                    if (ValidateUtil.isEmptyObjectOrString(comment.getType())) {
                        comment.setType(0);
                    }
                    if (comment.getType().equals(1)) {
                        MarketingSeckill marketingSeckill = marketingSeckillService.getMarketingSeckillByProductId(detail.getId());
                        if (marketingSeckill == null) {
                            return ResultVo.error("无此活动!");
                        }
                        comment.setType(0);
                        comment.setProductId(marketingSeckill.getProductId().intValue());
                    } else if (comment.getType().equals(2)) {
                        List<MarketingGroup> marketingGroupList = marketingGroupService.getMarketingGroupByProductId(detail.getId());
                        if (marketingGroupList.size() == 0) {
                            return ResultVo.error("无此活动!");
                        }
                        MarketingGroup marketingGroup = marketingGroupList.get(0);
                        //大礼包类拼团单独处理
                        if (marketingGroup.getMarketingGroupType().equals(1)) {
                            comment.setType(1);
                            comment.setProductId(detail.getId().intValue());
                        } else {
                            comment.setType(0);
                            comment.setProductId(marketingGroup.getProductId().intValue());
                        }
                    } else {
                        comment.setProductId(detail.getId().intValue());
                    }
//				comment.setProductId(detail.getId().intValue());
                    comment.setCentreId(detail.getCentreId());
                    comment.setProductName(detail.getTitle());
                    productCommentService.addProductComment(comment);

                    //更新商品状态
                    orderProduct.setStatus(6);
                    orderProductMapper.updateByPrimaryKeySelective(orderProduct);

                    centreId = detail.getCentreId();
                }
            }
        }else if(comment.getType() == 1){
            comment.setProductId(ops.get(0).getProductId().intValue());
            productCommentService.addProductComment(comment);
        }else if(comment.getType() == 2){
            comment.setProductId(ops.get(0).getActivityId().intValue());
            productCommentService.addProductComment(comment);
        }else if(comment.getType() == 3){
            comment.setProductId(ops.get(0).getActivityId().intValue());
            productCommentService.addProductComment(comment);
        }

        //商家评分
        if (centreId > 0L) {
            Map param = new HashMap<>();
            param.put("centreId", centreId);
            BigDecimal grade = productCommentService.getCentreGrade(param);

            Centre centre = new Centre();
            centre.setCentreId(centreId);
            centre.setGrade(grade);
            centreService.updateCentre(centre);

            //完成订单
            order.setCommentStatus(1);
            orderService.completeOrder(order);

            //计算积分
//			double exchange = 100d;
//			TradeConfig config = configService.getTradeConfig(comment.getCentreId());
//			if (config != null && config.getExchangeIntegral() != null) {
//				exchange = config.getExchangeIntegral();
//			}
//			orderService.autoCompleteOrder(ops, comment.getCentreId(), exchange);
        }

        resultVo.put("success", true);
        resultVo.put("data", comment);
        return resultVo;
    }

    /**
     * 获取商品销售量以及库存，在菜单之间切换使用
     *
     * @RequestParam("id[]") List<Long> products, Long memberId, Long shopId
     */
    @RequestMapping("/sales")
    @ResponseBody
    public ResultVo getProductSales(@RequestBody CartDelallVo vo) {
        List<Long> products = Arrays.asList(vo.getId().split(","))
                .stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList()); //测点数组
        Map<Long, SalesStockVo> stocks = productCentreService.getProductSalesStocks(products,
                vo.getMemberId());
        ResultVo resultVo = new ResultVo();
        resultVo.put("success", true);
        JSONObject jsonObject = new JSONObject();

        for (Map.Entry stock : stocks.entrySet()) {
            jsonObject.put(stock.getKey().toString(), stock.getValue());
        }

        resultVo.put("data", jsonObject);


        resultVo.put("time", System.currentTimeMillis());
        return resultVo;
    }



}
